import {observable as o, computed as c, action as a} from 'mobx';
import _ from 'lodash';
import axios from 'core/axios';
import RootStore from 'core/Store.js';
import request from 'core/request.js';
import Im from 'immutable';
import {browserHistory} from 'react-router';

class Store extends RootStore {
    constructor(args) {
        super(args);
    }

    will() {

    }

    @o menuList = [];
    @o toggleList = [];

    @a
    innerJump(href) {
        if (browserHistory.getCurrentLocation().pathname === href) {
            return;
        }
        browserHistory.push(href);
    }

    @a
    toggleShow(id) {
        let mIndex = this.toggleList.findIndex((i) => {
            return i === id;
        });
        if (mIndex > -1) {
            this.toggleList = this.toggleList.filter((i) => {
                return i !== id;
            });
        } else {
            this.toggleList.push(id);
        }
    }

    @a
    getMenuList() {
        request({
            method: 'get', url: $$.api('getMenuList'),
        }).then(res => {
            if (res.data) {
                if (res.data.id === -1) {//是否是顶级节点，代表父级，并且子级大于等于2条
                    this.menuList = res.data.children;
                } else {
                    this.menuList = [];
                    this.menuList.push(res.data);
                }
            } else {
                this.menuList = [];
            }
            if (this.menuList.length > 0) {
                let mIndex = this.menuList.findIndex(item => {
                    return item.attributes.url === browserHistory.getCurrentLocation().pathname;
                })
                if (!~mIndex) {
                    browserHistory.replace($$.url('home'));
                }
            } else {
                browserHistory.replace($$.url('home'));
            }
            this.fire('menu:load');
        }).catch(err => {
            this.stores.Message.fire('message', {type: $$.SEM.ERROR_TEXT, text: err.message});
        });
    }

    @o
    loginOut() {
        request({method: 'get', url: $$.api('exitLogin')}).then(res => {
            $$.utils.delCookie('sessionId', '');
            global.window.location.href = $$.url('login');
        }).catch(err => {
            this.loading = false;
            if (err.code === $$.SEM.USER_NOT_LOGIN_ERROR_CODE || err.message === '用户未登录') {
                $$.utils.delCookie('sessionId', '');
            }
        });
    }


    mount() {
        this.getMenuList();
    }

}

export default Store;